<?php

namespace Trawind\AliOSS;

use Trawind\AliOSS\Plugins\DownloadObject;
use Trawind\AliOSS\Plugins\ListObjects;
use Trawind\AliOSS\Plugins\PutRemoteFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use OSS\OssClient;

class AliOssServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {

        Storage::extend('oss', function($app, $config)
        {
            $accessId  = $config['access_id'];
            $accessKey = $config['access_key'];

            $cdnDomain = empty($config['cdnDomain']) ? '' : $config['cdnDomain'];
            $bucket    = $config['bucket'];
            $ssl       = empty($config['ssl']) ? false : $config['ssl'];
            $isCname   = empty($config['isCName']) ? false : $config['isCName'];
            $isMultipart   = empty($config['isMultipart']) ? false : $config['isMultipart'];
            $debug     = empty($config['debug']) ? false : $config['debug'];

            $endPoint  = $config['endpoint'];
            $epInternal= $isCname ? $cdnDomain : (empty($config['endpoint_internal']) ? $endPoint : $config['endpoint_internal']);

            $size  = $isMultipart ? isset($config['size']) ? $config['size'] : null : null;

            if($debug) Log::debug('OSS config:', $config);

            $client  = new OssClient($accessId, $accessKey, $epInternal, $isCname);
            $adapter = new AliOssAdapter($client, $bucket, $endPoint, $ssl, $isCname, $debug, $cdnDomain, $isMultipart, $size);

            $filesystem =  new Filesystem($adapter);
            $filesystem->addPlugin(new PutRemoteFile());
            $filesystem->addPlugin(new DownloadObject($config));
            $filesystem->addPlugin(new ListObjects());

            return $filesystem;
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
    }
}
